<template>
	<view class="cart_main">
		<!-- 购物车页面 -->
		<view class="return_and_text">
			<view class="return_cancel" @click="returnPage">
				<uni-icons type="arrow-left" size="28"></uni-icons>
			</view>
			<view class="edit_or_complete" @click="changeCartState" v-if="!isCartEmpty">
				{{cartStateText}}
			</view>
		</view>
		<view class="cart_text">
			购物车
		</view>
		<view class="my_records">
			<view class="my_records_text">
				我的积分：
			</view>
			<view class="my_records_icon">
				<image :src="recordImg" mode="aspectFill" class="record_icon"></image>
			</view>
			<view class="record_num_text">
				{{recordNum}}
			</view>
		</view>

		<!-- 分割线 -->
		<view class="divider_line"></view>

		<!-- 购物车商品 -->
		<view class="cart_goods" v-if="!isCartEmpty">
			<view class="cart_good_per" v-for="(item,index) in cartGoods" :key="index">
				<view class="check_box">
					<label>
						<radio :value="item.goodName" :checked="item.isChecked" active-background-color="#01c6c1"
							@click="changeRadioState(item)" />
					</label>
				</view>
				<view class="good_image" @click="toGoodsDetailPage">
					<image :src="item.goodimg" mode="aspectFill" class="good_image_src"></image>
				</view>
				<view class="good_desc">
					<view class="good_top_desc">
						<view class="title_and_num">
							<view class="title_good">
								{{item.goodName}}
							</view>
							<view class="good_number">
								<view class="jianhao" @click="jianGoodNum(item,index)">
									-
								</view>
								<view class="good_number_text">
									<input type="number" v-model="item.selectedNum" @confirm="updateCartGoods(item)"
										@blur="updateCartGoods(item)" />
								</view>
								<view class="jiahao" @click="jiaGoodNum(item,index)">
									+
								</view>
							</view>
						</view>
						<view class="selected_style">
							{{item.selectStyle}}
						</view>
					</view>
					<view class="price_and_records">
						<view class="price_goods_text">
							￥{{item.price}}
						</view>
						<view class="record_good_icon_text">
							<view class="record_icon_view">
								<image :src="recordImg" mode="aspectFill" class="record_icon"></image>
							</view>
							<view class="records_num_text">
								{{item.records}}
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部购买，删除导航 -->
		<view class="calculate_allPrice_sell" v-if="!isCartEmpty">
			<view class="select_all">
				<radio :checked="isSelectAll" active-background-color="#01c6c1" @click="selectAll" /><text>全选</text>
			</view>
			<view class="footer_right_part">
				<view class="total_price" v-if="!isEditState">
					￥{{totalPrice}}
				</view>
				<view class="buy_now">
					<button class="but_now_btn" @click="buyOrDeleteFunc">{{buyOrDelete}}</button>
				</view>
			</view>
		</view>

		<!-- 如果购物车是空的，就显示下面 -->
		<view class="empty_cart_main" v-if="isCartEmpty">
			<view class="empty_cart_image">
				<image :src="emptyCartImage" mode="aspectFill" class="empty_image"></image>
			</view>
			<view class="empty_text">
				购物车还是空的，去添加点什么吧！
			</view>
			<view class="toShoppingFirstPage" @click="toShoppingFirstPage">
				<button>去逛逛</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getMyCartInfo,
		deleteCartGoods
	} from '@/request/goods.js'
	export default {
		data() {
			return {
				// 这里可以定义组件的数据
				cartStateText: '编辑', // 购物车的状态：编辑，完成
				recordImg: '../../../../static/icons/integral.png',
				recordNum: 0, // 积分,
				isSelectAll: true, // 控制是否全选
				totalPrice: '0.0', // 总价
				buyOrDelete: '立即购买', // 立即购买，删除所选
				isEditState: false, // 点击编辑进入编辑状态，变为true
				emptyCartImage: '../../../../static/image/cart.png', // 空的购物车图片
				isCartEmpty: false, // 购物车是否为空
				cartGoods: [
					// {
					// 	isChecked: true,
					// 	goodimg: 'https://img0.baidu.com/it/u=1998075800,1711290088&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1422',
					// 	goodName: 'NOMI可调节挂绳',
					// 	price: 49,
					// 	records: 490,
					// 	selectedNum: 1,
					// 	selectStyle: '灰色',
					// },
					// {
					// 	isChecked: true,
					// 	goodimg: 'https://img0.baidu.com/it/u=924792725,4074648822&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500',
					// 	goodName: '发光键盘',
					// 	price: 200,
					// 	records: 2000,
					// 	selectedNum: 1,
					// 	selectStyle: '茶轴（白光版）',
					// },
					// {
					// 	isChecked: true,
					// 	goodimg: 'https://img1.baidu.com/it/u=2750699102,1507422084&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=500',
					// 	goodName: '的卢2代越野跑鞋 男款',
					// 	price: 899,
					// 	records: 8990,
					// 	selectedNum: 34,
					// 	selectStyle: '冷檀黑 41码'
					// },
					// {
					// 	isChecked: true,
					// 	goodimg: 'https://img0.baidu.com/it/u=2715046952,1515877868&fm=253&fmt=auto?w=1028&h=800',
					// 	goodName: 'Urban 折叠自行车',
					// 	price: 3410,
					// 	records: 34100,
					// 	selectedNum: 1,
					// 	selectMenu: '蓝色',
					// },
					// {
					// 	isChecked: true,
					// 	goodimg: 'https://img1.baidu.com/it/u=3230294336,864843562&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
					// 	goodName: '小熊新品',
					// 	price: 50,
					// 	records: 500,
					// 	selectedNum: 1,
					// 	selectMenu: '',
					// },
				],
			};
		},

		methods: {

			// 获取我的购物车信息
			getCartInfos() {
				getMyCartInfo().then(res => {
					// console.log(res);
					this.recordNum = res.data.data.recordNum;
					if (res.data.data.cartGoods === null) {
						this.isCartEmpty = true;
					} else {
						this.cartGoods = res.data.data.cartGoods;
					}
				}).catch(err => {
					console.log(err);
					uni.showToast({
						title: '系统异常',
						icon: 'error'
					})
				})
			},

			// 这里可以定义组件的方法
			returnPage() {
				uni.navigateBack();
			},
			// 改变购物车状态
			changeCartState() {
				if (this.cartStateText === '编辑') {
					this.cartStateText = '完成';
					this.isEditState = true;
					this.buyOrDelete = '删除所选';
				} else {
					this.cartStateText = '编辑';
					this.isEditState = false;
					this.buyOrDelete = '立即购买';
				}
			},
			// 购物车商品的名称太长就截取
			filterCartGoods() {
				const newCartGoods = this.cartGoods.map((item) => {
					var newName = item.goodName;
					if (item.goodName.length > 6) {
						newName = item.goodName.substring(0, 6).toString() + '...';
					}
					return {
						...item,
						goodName: newName
					};
				});
				this.cartGoods = newCartGoods;
			},
			// 点击减号减少数量
			jianGoodNum(item, index) {
				if (item.selectedNum > 1) {
					item.selectedNum--;
				} else {
					uni.showToast({
						title: '最低购买一个',
						icon: 'none'
					})
				}
				// 计算总价
				this.calTotalPrice();
			},
			// 点击加号增加数量
			jiaGoodNum(item, index) {
				item.selectedNum++;
				// 计算总价
				this.calTotalPrice();
			},
			// 直接输入数字，更改商品的数量
			updateCartGoods(item) {
				if (item.selectedNum < 1) {
					uni.showToast({
						title: '最低购买一个',
						icon: 'none'
					})
					item.selectedNum = 1;
				}
			},
			// 点击radio，改变勾选状态
			changeRadioState(item) {
				item.isChecked = !item.isChecked;
				// 如果没勾选，那么就代表全选按钮的状态为false
				if (!item.isChecked) {
					this.isSelectAll = false;
				}
				// 计算总价
				this.calTotalPrice();
			},

			// 计算总价
			calTotalPrice() {
				let newTotalPrice = 0;
				this.cartGoods.forEach((item) => {
					if (item.isChecked) {
						newTotalPrice += item.price * item.selectedNum;
					}
				})
				this.totalPrice = newTotalPrice.toFixed(1)
			},

			// 全选
			selectAll() {
				if (this.isSelectAll) {
					this.cartGoods.forEach((item) => {
						item.isChecked = false;
					});
					// 全选为false，购物车所有商品价格总价为0
					this.totalPrice = '0.0';
				} else {
					// 全部商品价格相加（单价 * 数量）isChecked改为true
					let allPrice = 0;
					this.cartGoods.forEach((item) => {
						item.isChecked = true;
						allPrice += item.price * item.selectedNum;
					})
					this.totalPrice = allPrice.toFixed(1);
				}
				this.isSelectAll = !this.isSelectAll;
			},
			// 点击立即购买或者删除所有
			buyOrDeleteFunc() {
				const _this = this;
				if (!this.isEditState) {
					// 立即购买，发起订单,去立即结算页面
					let newGoods = [];
					_this.cartGoods.forEach((item) => {
						if (item.isChecked) {
							newGoods.push(item);
						}
					});
					let order = {
						totalPrice: _this.totalPrice,
						cartGoods: newGoods
					}
					uni.setStorageSync('order', order);
					uni.navigateTo({
						url: '/pages/order/payMentSettle'
					})

				} else {
					// 删除所选
					uni.showModal({
						title: '确定删除吗？',
						success: function(res) {
							if (res.confirm) {
								const removeCartGoods = _this.cartGoods.filter((element) => element.isChecked);
								const data = [];
								removeCartGoods.forEach(item => {
									let obj = {
										cartAid: item.cartAid,
										goodAid: item.goodAid,
										selectStyle: item.selectStyle
									}
									data.push(obj);
								})
								// console.log(data);
								// 向后端发送请求保存所选的
								deleteCartGoods(data).then(res => {
									console.log(res);
									if (res.data.code === 10000) {
										uni.showToast({
											title: '删除成功！',
											icon: 'success'
										})
										_this.cartGoods = _this.cartGoods.filter((element) => !element.isChecked);
									} else {
										uni.showToast({
											title: '请稍后再试！',
											icon: 'error'
										})
									}
								}).catch(err => {
									console.log(err);
									uni.showToast({
										title: '请稍后再试！',
										icon: 'error'
									})
								})
								// 判断购物车是否为空
								_this.checkCartEmpty();
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
				}
			},
			// 去购物首页
			toShoppingFirstPage() {
				uni.switchTab({
					url: '/pages/tabBar/extUI/extUI'
				})
			},
			// 判断购物车是否为空
			checkCartEmpty() {
				if (this.cartGoods.length === 0) {
					this.isCartEmpty = true;
				} else {
					this.isCartEmpty = false;
				}
			},
			// 去商品详情页面
			toGoodsDetailPage() {
				uni.navigateTo({
					url: '/pages/tabBar/extUI/shopping_topBar/goodDetail'
				})
			}
		},
		onLoad() {
			// console.log('onLoad获取信息');
			// 获取我的购物车信息
			this.getCartInfos();
			// 过滤商品名称
			this.filterCartGoods();
			// 判断购物车是否为空
			this.checkCartEmpty();
			// 计算购物车选中的商品总价
			this.calTotalPrice();
		}
	};
</script>

<style scoped>
	/* 这里是组件的样式 */
	.cart_main {
		padding: 30rpx;
		padding-top: 60rpx;
	}

	.cart_text {
		margin-top: 20rpx;
		font-size: 60rpx;
	}

	.return_and_text {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}

	.edit_or_complete {
		font-size: 35rpx;
	}

	.record_icon {
		width: 30rpx;
		height: 30rpx;
	}

	.my_records {
		margin-top: 30rpx;
		display: flex;
		flex-direction: row;
	}

	.record_num_text {
		margin-left: 10rpx;
	}

	.record_num {
		margin-left: 10rpx;
	}

	.divider_line {
		margin-top: 50rpx;
		margin-bottom: 50rpx;
		border-top: 1px solid;
		border-top-color: #e5e5e5;
	}

	.good_image_src {
		width: 200rpx;
		height: 200rpx;
	}

	.checkbox_class {
		border-radius: 50%;
	}

	.cart_goods {
		margin-top: 30rpx;
		padding-bottom: 200rpx;
	}

	.cart_good_per {
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
	}

	.good_image {
		margin-left: 20rpx;
	}

	.title_and_num {
		display: flex;
		justify-content: space-between;
	}

	.title_good {
		font-size: 35rpx;
		word-wrap: break-word;
	}

	.good_desc {
		width: 60%;
		margin-left: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		height: 200rpx;
	}

	.good_number {
		width: 100rpx;
		height: 40rpx;
		display: flex;
		justify-content: space-around;
		border: 1px solid;
		border-color: #e5e5e5;
		border-radius: 5rpx;
		padding-left: 20rpx;
		padding-right: 20rpx;
	}

	.jianhao {
		display: flex;
		align-items: center;
		font-size: 40rpx;
	}

	.jiahao {
		display: flex;
		align-items: center;
		font-size: 30rpx;
	}

	.good_number_text {
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.good_number_text input {
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.selected_style {
		color: #949494;
	}

	.price_and_records {
		display: flex;
	}

	.record_good_icon_text {
		display: flex;
		align-items: center;
	}

	.price_goods_text {
		font-size: 35rpx;
		font-weight: 600;
	}

	.record_good_icon_text {
		margin-left: 20rpx;
	}

	.records_num_text {
		margin-left: 8rpx;
		font-size: 35rpx;
		font-weight: 600;
	}

	.record_icon_view {
		display: flex;
		align-items: center;
	}

	.calculate_allPrice_sell {
		position: fixed;
		z-index: 100;
		bottom: 0;
		background-color: #f5f5f5;
		width: 90%;
		height: 150rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.footer_right_part {
		display: flex;
		align-items: center;
	}

	.total_price {
		font-size: 40rpx;
		font-weight: 600;
	}

	.buy_now {
		margin-left: 15rpx;
	}

	.but_now_btn {
		border-radius: 50rpx;
		background-color: #01c6c1;
		color: #f4f4f4;
	}

	.empty_image {
		width: 300rpx;
		height: 300rpx;
		opacity: 0.2;
	}

	.empty_cart_image {
		display: flex;
		justify-content: center;
	}

	.empty_cart_main {
		margin-bottom: 300rpx;
	}

	.empty_text {
		text-align: center;
		margin-top: 100rpx;
		font-size: 40rpx;
		color: #bababa;
	}

	.toShoppingFirstPage {
		margin-top: 100rpx;
	}

	.toShoppingFirstPage button {
		background-color: #66596b;
		border-radius: 50rpx;
		color: #fff;
		letter-spacing: 10rpx;
	}
</style>